package com.wangtianxiang.sxp.weixin.helper;

import com.wangtianxiang.sxp.domain.Jscode2sessionRes;
import com.wangtianxiang.sxp.po.SysConfig;
import com.wangtianxiang.sxp.module.service.SysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
@Slf4j
public class WxHelper {

    @Autowired
    private SysConfigService sysConfigService;

    @Autowired
    private RestTemplate restTemplate;

    public Jscode2sessionRes code2sessionKey(String code){
        String uri = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";
        SysConfig appIdConfig = sysConfigService.getById("wx_appid");
        SysConfig secretConfig = sysConfigService.getById("wx_secret");
        if(appIdConfig == null || secretConfig == null){
            log.info("wx_appid或wx_secret配置不存在!");
            throw new RuntimeException("wx_appid或wx_secret配置不存在!");
        }
        String url = String.format(uri,appIdConfig.getValue(),secretConfig.getValue(),code);
        return restTemplate.getForObject(url,Jscode2sessionRes.class);
    }
}
